from flask import Blueprint, request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from utils.response import success_response, error_response, login_success_response

auth_bp = Blueprint('auth', __name__)

# 模拟用户数据库
USERS = {
    "admin": {
        "id": 1,
        "username": "admin",
        "password": "123456",  # 实际项目中应该加密
        "email": "admin@example.com",
        "role": "admin"
    },
    "user": {
        "id": 2,
        "username": "user",
        "password": "123456",
        "email": "user@example.com",
        "role": "user"
    },
    "asdfgh": {  # 添加您的测试用户
        "id": 3,
        "username": "asdfgh",
        "password": "123456",
        "email": "asdfgh@example.com",
        "role": "user"
    }
}

@auth_bp.route('/api/user/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        if not data:
            return error_response("请求数据为空", 400)
        
        username = data.get('username', '').strip()
        password = data.get('password', '').strip()
        
        if not username or not password:
            return error_response("用户名和密码不能为空", 400)
        
        # 验证用户
        user = USERS.get(username)
        if not user or user['password'] != password:
            return error_response("用户名或密码错误", 401)
        
        # 创建JWT token
        access_token = create_access_token(identity=username)
        
        # 返回用户信息（不包含密码）
        user_data = {
            "id": user["id"],
            "username": user["username"],
            "email": user["email"],
            "role": user["role"]
        }
        
        return login_success_response(user_data, access_token)
        
    except Exception as e:
        print(f"登录错误: {str(e)}")
        return error_response("服务器内部错误", 500)

@auth_bp.route('/api/user/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        print(f"📝 收到注册请求数据: {data}")
        
        if not data:
            print("❌ 请求数据为空")
            return error_response("请求数据为空", 400)
        
        username = data.get('username', '').strip()
        password = data.get('password', '').strip()
        email = data.get('email', '').strip()
        
        print(f"📝 注册尝试: 用户名={username}, 邮箱={email}, 密码长度={len(password)}")
        print(f"📋 注册前用户列表: {list(USERS.keys())}")
        
        if not username:
            print("❌ 用户名为空")
            return error_response("用户名不能为空", 400)
            
        if not password:
            print("❌ 密码为空")
            return error_response("密码不能为空", 400)
            
        if not email:
            print("❌ 邮箱为空")
            return error_response("邮箱不能为空", 400)
        
        if username in USERS:
            print(f"❌ 用户名已存在: {username}")
            return error_response("用户名已存在", 400)
        
        # 添加新用户
        new_user_id = len(USERS) + 1
        USERS[username] = {
            "id": new_user_id,
            "username": username,
            "password": password,
            "email": email,
            "role": "user"
        }
        
        print(f"✅ 注册成功: {username}")
        print(f"📋 注册后用户列表: {list(USERS.keys())}")
        
        return success_response(message="注册成功")
        
    except Exception as e:
        print(f"💥 注册错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return error_response("服务器内部错误", 500)

@auth_bp.route('/api/user/info', methods=['GET'])
@jwt_required()
def get_user_info():
    """获取用户信息"""
    try:
        current_user = get_jwt_identity()
        user = USERS.get(current_user)
        
        if not user:
            return error_response("用户不存在", 404)
        
        user_data = {
            "id": user["id"],
            "username": user["username"],
            "email": user["email"],
            "role": user["role"]
        }
        
        return success_response(user_data)
        
    except Exception as e:
        print(f"获取用户信息错误: {str(e)}")
        return error_response("服务器内部错误", 500)

# 在文件最后添加调试接口
@auth_bp.route('/api/debug/users', methods=['GET'])
def debug_users():
    """调试：查看所有用户"""
    return success_response({
        "users": list(USERS.keys()),
        "count": len(USERS),
        "details": {k: {**v, "password": "***"} for k, v in USERS.items()}
    })